package model;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

/**
 *
 * @author Dustin
 */
public class ReceiveThread extends Thread{
    private Socket socket;
    private ObjectInputStream inputStream;
    private Queue inputQueueQueue;

    public ReceiveThread(Socket aSocket, Queue aQueue) {
        socket = aSocket;
        try {
            inputStream = new ObjectInputStream(socket.getInputStream());
            inputQueueQueue = aQueue;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(true) {
            try {
                Packet p = (Packet) inputStream.readObject();
                if(Math.random() > Packet.TRESHHOLD) {
                    inputQueueQueue.enqueue(p);
                    System.out.println(System.currentTimeMillis() + " Received frame: " + p.getSeq());
                } else {
                    System.out.println("Lost packet " + p.getSeq());
                }
            } catch (IOException ex) {
                disconnect();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void disconnect() {
        try {
            inputStream.close();
            socket.close();
            System.exit(0);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
